package cc.customer.onschool.services.impl;

import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.FebsUtil;
import cc.customer.cusDynamic.domain.CusDynamic;
import cc.customer.cusDynamic.services.CusDynamicService;
import cc.customer.onschool.dao.OnSchoolResourceMapper;
import cc.customer.onschool.domain.OnSchoolResource;
import cc.customer.onschool.services.OnSchoolService;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import cc.customer.utils.AutonCusInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service("OnSchoolService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OnSchoolServiceImpl extends BaseService<OnSchoolResource> implements OnSchoolService {

   private Logger logger = LoggerFactory.getLogger(OnSchoolServiceImpl.class);

   @Autowired
   private OnSchoolResourceMapper mapper;
   @Autowired
   private CusDynamicService cusDynamicService;


   @Override
   public int batchInsertByCode(List<OnSchoolResource> list){
      return mapper.insertList(list);
   }


   @Override
   public List<OnSchoolResource> selectByResource(OnSchoolResource resource,MyUser user){
      try {
         Example example = new Example(OnSchoolResource.class);
         Example.Criteria criteria = example.createCriteria();
         Example.Criteria criteria2 = example.createCriteria();
         /**按昵称搜索**/
         String batch = resource.getOsNickname();
         if(!StringUtils.isEmpty(batch)){
            criteria.andLike("osNickname","%"+batch+"%");
         }
         String starttime =  resource.getStarttime();
         String endtime = resource.getEndtime();
         if (!StringUtils.isAnyEmpty(starttime,endtime)){
            criteria.andBetween("osCreateTime",starttime,endtime+" 23:59:59");

         }else if (!StringUtils.isEmpty(starttime)){
            criteria.andCondition("osCreateTime = ",starttime);
         }
         criteria.andIsNull("osMyCustomer").orEqualTo("osMyCustomer","");
         criteria2.andNotEqualTo("osDealStatus","2");
         example.and(criteria2);
         example.setOrderByClause("os_create_time desc");
         List<OnSchoolResource> list = this.selectByExample(example);
         for (OnSchoolResource reource:list){
            AutonCusInfo.parseOnSchoolResource(reource,user);
         }
         return list;
      }catch (Exception e){
         return new ArrayList<>();
      }
   }
   @Override
   public List<OnSchoolResource> selectOnResByTimeAndUser(String starttime, String endtime, String userid) {
      try {
         Example example = new Example(OnSchoolResource.class);
         Example.Criteria criteria = example.createCriteria();
         criteria.andBetween("osCreateTime",starttime,endtime).andEqualTo("osMyCustomer",userid);
         return this.selectByExample(example);
      }catch (Exception e){
         logger.error("获取网校资源失败:"+e.getMessage());
      }
      return new ArrayList<>();
   }

   /**导出客户*/
   @Override
   public List<OnSchoolResource> exportOnschoolInfo(String exportids,MyUser user) {
      String []exportsIds  = exportids.split(",");
      List<String> ids = new ArrayList<>();
      for(String id:exportsIds){
         ids.add(id);
      }
      Example example = new Example(OnSchoolResource.class);
      example.createCriteria().andIn("osId",ids);
      List<OnSchoolResource> emp =  this.selectByExample(example);
      for (OnSchoolResource onSchoolResources:emp){
         AutonCusInfo.parseOnSchoolResource(onSchoolResources,user);
      }

      return emp;
   }

   /**批量更新客户的信息**/
   @Override
   @Transactional
   public ResponseBo batchUpdateBykeyId(OnSchoolResource resource, String ids,String names,String userid)throws RuntimeException {
      try {
         List<String> list = Arrays.asList(ids.split(","));
         int num =  this.batchUpdate(list,"osId",OnSchoolResource.class,resource);
         if (num > 0){
            /**增加操作记录**/
            cusDynamicService.batchInsertWxEmpDisture(list,resource);
            return ResponseBo.ok("更新客户的信息成功");
         }
      }catch (Exception e){
         e.printStackTrace();
         logger.error("更新客户失败:"+e.getMessage());
         return ResponseBo.error("更新客户的信息失败");
      }
      return ResponseBo.ok("更新客户的信息成功");
   }

   @Override
   public ResponseBo findCustomerDetailByid(String keyid, MyUser user) {
      try {
         OnSchoolResource resource = mapper.findCustomerDetailByid(keyid);
         OnSchoolResource onSchoolResource = AutonCusInfo.parseOnSchoolResource(resource,user);
         return  ResponseBo.ok(onSchoolResource);
      }catch (Exception e){
         logger.error("获取客户资料失败 :"+e.getMessage());
      }
      return ResponseBo.error("获取客户资料失败");
   }

   @Override
   public ResponseBo AppFindCustomerDetailByid(String keyid, MyUser user) {
      try {
         OnSchoolResource resource = mapper.appfindCustomerDetailByid(keyid);
         return  ResponseBo.ok(resource);
      }catch (Exception e){
         logger.error("获取客户资料失败 :"+e.getMessage());
      }
      return ResponseBo.error("获取客户资料失败");
   }


   @Override
   public ResponseBo selectOnshoolLabel(String osid) {
      try {
         OnSchoolResource list = mapper.selectOnshoolLabel(osid);
         return ResponseBo.ok(list);
      }catch (Exception e){
         logger.error("获取网校资源客户的标签失败："+e.getMessage());
      }
      return ResponseBo.error();
   }

   /**修改客户资料*/
   @Override
   @Transactional
   public ResponseBo updateOnshoolEmpInfoByBpId(OnSchoolResource resource,MyUser user) {
      try {
         /**如果更新得是手机号，则验证手机号 是不是存在 如果存在 则不能更新**/
         String mobilePhone = resource.getOsMobile();
         if (!StringUtils.isEmpty(mobilePhone)){
            //验证手机号
            Boolean ble = FebsUtil.isPhoneNo(mobilePhone);
            if (!ble){
               return ResponseBo.error("当前手机号不正确，不允许更新");
            }
            OnSchoolResource isHave = findBigEmpByMobile(mobilePhone);
            if (isHave !=null){
               return ResponseBo.error("当前手机号已经存在，不允许更新");
            }
         }
         int num = this.updateNotNull(resource);
         if (num <= 0){
            return ResponseBo.error("修改失败,修改条目:"+num);
         }
      }catch (Exception e){
         logger.error("修改客户得信息失败:"+e.getMessage());
         return ResponseBo.error("修改客户得信息失败:"+e.getMessage());
      }
      if (!StringUtils.isEmpty(resource.getOsStage())){
         List<String> list = new ArrayList<>();
         list.add(resource.getOsId()+"");
         CusDynamic cus = new CusDynamic();
         cus.setDyCreator(user.getUserUuid());
         cus.setDyType(Constant.CUSTOMER_RECORD_STATAGES);
         cus.setDySourceType("2");
         String stta = AutonCusInfo.parseCustomerStage(resource.getOsStage());
         cus.setDyContent(user.getNickname()+" 更改了客户阶段: "+stta);
         cusDynamicService.inserDynamic(list,cus);
      }


      return ResponseBo.ok("修改客户资料成功");
   }

   public OnSchoolResource findBigEmpByMobile(String Mobile) {
      Example example = new Example(OnSchoolResource.class);
      example.createCriteria().andCondition("os_mobile=",Mobile);
      List<OnSchoolResource> list = this.selectByExample(example);
      return list.isEmpty() ? null : list.get(0);
   }

   @Override
   public int deleteSchoolResource() {
      return mapper.deleteSchoolResource();
   }

   @Override
   public List<String> selectSchoolPhone() {
      return mapper.selectSchoolPhone();
   }
}
